from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
import datetime

from web import models


class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.tracer = Tracer()
        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()

        request.tracer.user = user_object

        # 白名单
        # 获取当前url，url是否在白名单中
        url = request.path_info
        if url in settings.WHITE_REGEX_URL_LIST:
            return

        # 检查用户是否登录
        if not request.tracer.user:
            # 未登录，返回到登录页面
            return redirect("login")

        # 登录成功后，访问后台管理是：获取当前用户所拥有的额度
        # 方式一
        # 获取最近交易记录
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by("-id").first()
        current_time = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_time:
            # vip已过期，设置为免费版
            _object = models.Transaction.objects.filter(user=user_object, status=2, price_policy__category=1).first()

        # 获取额度
        request.tracer.price_policy = _object.price_policy

        """
        # 方式二
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by("-id").first()
        if not _object:
            # 没有购买
            request.price_policy = models.Transaction.objects.filter(category=1, title="个人免费版").first()
        else:
            # 付费，已过期
            current_datetime = datetime.datetime.now()
            if _object.end_datetime and _object.end_datetime < current_datetime:
                request.price_policy = models.Transaction.objects.filter(category=1, title="个人免费版").first()
            else:
                request.price_policy = _object.price_policy
        """

    def process_view(self, request, view, args, kwargs):
        project_id = kwargs.get("project_id")
        # path = request.path_info.startswith("/manage/")
        if not request.path_info.startswith("/manage/"):
            return

        # 当前用户创建的项目
        project_obj = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_obj:
            request.tracer.project = project_obj
            return

        # 当前用户参与的项目
        project_user_obj = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_obj:
            request.tracer.project = project_user_obj.project
            return

        return redirect("project_list")
